package com.briup.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/13
 * @Description:
 */
class Plate{
    public int num;
    public boolean isEmpty=true;
}
class Producter extends Thread{
    private Plate plate;
    public Producter(String name,Plate plate){
        super(name);
        this.plate=plate;
    }

    @Override
    public void run() {
        for (int i = 0; i <100 ; i++) {
            synchronized (plate) {
                //没有包子，生产，通知消费者
                if(plate.isEmpty) {
                    plate.num++;
                    System.out.println(this.getName() + "生产了一个包子：" + this.plate.num);
                    this.plate.isEmpty=false;
                    plate.notify();
                }else{
                    //生产者：有包子，就不生产，等待
                    try {
                        plate.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
class Custormer extends Thread{
    private Plate plate;

    public Custormer(String name, Plate plate) {
        super(name);
        this.plate = plate;
    }

    @Override
    public void run() {
        for (int i = 0; i <100 ; i++) {
            synchronized (plate) {
                //有包子，吃，通知生产者
                if(!this.plate.isEmpty) {
                    plate.num--;
                    System.out.println(this.getName() + "消费了一个包子：" + this.plate.num);
                    this.plate.isEmpty=true;
                    this.plate.notify();
                }else{
                    try {
                        //没有包子，等待
                        this.plate.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
//生产者：有包子，就不生产，等待
//没有包子，生产，通知消费者
//消费者：有包子，吃，通知生产者
//没有包子，等待
public class Test11 {
    public static void main(String[] args) {
        Plate plate=new Plate();
        Thread t1=new Producter("生产者",plate);
        Thread t2=new Custormer("消费者",plate);
        t1.start();
        t2.start();
    }
}
